package com.heima.wemedia.service.impl;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.wemedia.service.WmSensitiveService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author jay
 * @date 2022/11/17 18:32:20
 */
public class ExcelService extends AnalysisEventListener<WmSensitive> {

    /**
     * 用于存储读取到的敏感词
     */
    private List<WmSensitive> list = new ArrayList<>();

    private WmSensitiveService wmSensitiveService;

    public ExcelService(WmSensitiveService wmSensitiveService){
        this.wmSensitiveService = wmSensitiveService;
    }


    /**
     * 每读取到一个数据就执行一次
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context analysis context
     */
    @Override
    public void invoke(WmSensitive data, AnalysisContext context) {
        if(data.getSensitives() == null){
            return;
        }
        if(data.getCreatedTime()==null){
            data.setCreatedTime(new Date());
        }
        list.add(data);
        System.out.println(data);
        if(list.size() >= 1000){
            saveDataBatch();
        }
    }

    /**
     * 解析表头的方法
     * 判断是否存在表头 "敏感词", 不存在就抛出异常
     * @param headMap
     * @param context
     */
    @Override
    public void invokeHeadMap(Map headMap, AnalysisContext context){
        for (Object itm : headMap.values()) {
            if("敏感词".equals(itm)){
                return;
            }
        }
        throw new CustomException(AppHttpCodeEnum.EXCEL_HEAD_NOT_EXISTS);
    }


    /**
     * 所有数据保存完之后会EasyExcel被调用
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveDataBatch();
    }

    /**
     * 批量保存数据
     */
    private void saveDataBatch(){
        wmSensitiveService.saveBatch(list);
        list.clear();
    }

}
